﻿using System;
using System.Linq;
using System.Web;
using db = DataContext;

namespace WebApplication.admin
{
	public partial class Images : System.Web.UI.Page
	{
		public int pid;
		public bool isadd, isdelete, issave;
		public int start, limit;
		public string info;

		protected void Page_Load(object sender, EventArgs e)
		{
			Common.CheckLogin();

			pid = int.Parse(Common.Query("pid"));
			isadd = Common.IsAdd;
			isdelete = Common.IsDelete;
			issave = Common.IsSave;

			start = Common.Start;
			limit = Common.Limit;

			using (db.DbDataContext context = new db.DbDataContext())
			{
				if (isadd)
				{
					info = context.Product.Single(x => x.Id == pid).Name;
				} else if (isdelete)
				{
					db.ProductPictures pic = context.ProductPictures.Single(x => x.Id == Common.Id);
					pid = pic.ProductId;
					System.IO.File.Delete(Server.MapPath("~/App_Data/Products/" + pic.GUID));
					System.IO.File.Delete(Server.MapPath("~/upload/products/" + pic.GUID + ".jpg"));
					context.ProductPictures.DeleteOnSubmit(pic);
					context.SubmitChanges();

					Response.Redirect("product_images.aspx?pid=" + pid + "&start=" + start + "&limit=" + limit);
				} else if (issave)
				{
					string guid = Guid.NewGuid().ToString();
					try
					{
						HttpPostedFile file = Request.Files["file"];
						Common.SaveThumbnail(file.InputStream, guid);

						context.ProductPictures.InsertOnSubmit(new db.ProductPictures()
						{
							GUID = guid,
							ProductId = pid,
							Size = file.ContentLength
						});
						context.SubmitChanges();
					} finally
					{
						Response.Redirect("product_images.aspx?pid=" + pid + "&start=" + start + "&limit=" + limit);
					}
				} else
				{
					i_list.DataSource = context.ProductPictures.Where(x => x.ProductId == pid);
					i_list.DataBind();
				}
			}
		}
	}
}